package com.eims.sls_app.ui;

import java.text.DecimalFormat;


import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.adapter.ExpandAdapterJCZQPassMore;
import com.eims.sls_app.ui.adapter.ExpandAdapterJCZQPassSingle;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.view.MyToast;

import bls.juejin.cn.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class ConfirmselectionActivity extends MyBaseActivity implements OnClickListener {

	protected static final String TAG = "ConfirmselectionActivity";
	private RadioGroup rg_secrecy;
	private RadioButton tab_open1, tab_end2, tab_secrecy3;
	private CheckBox cb_yongyin;
	private TextView tv_money, tv_needtopay, tv_Confirm_payment;
	private EditText et_context;
	private long sumCount, totalMoney;
	private int isStopChase;
	private Intent intent;
	private DecimalFormat format = new DecimalFormat("#####0.00");
	private Context context;
	public String opt, auth, info, time, imei, crc; // 格式化后的参数
	private MyHandler mHandler;
	private String context_Sun;
	private String max_jiangjin, stoptime,type;
	private MyAsynTask mMyAsynTask;
	private String SucJinECost, SucCaiJinCost, SuccMoney;
	private int secrecyLevel = 2;
	private boolean cancopy = true;
	private ImageButton btn_back;
	private ProgressDialog pd;
	private TextView  tvType;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_confirm_selection);
		App.activityS.add(this);
		App.activityS1.add(this);
		mHandler = new MyHandler();

		initView();
		enable();
		initText();
		initList();
	}

	private void initView() {
		Intent intent = getIntent();
		// requestUtil.commitBetting(sumCount, totalMoney, isStopChase);
		tvType=(TextView) findViewById(R.id.tv_type);
		sumCount = intent.getLongExtra("sumCount", 0);
		totalMoney = intent.getLongExtra("sumCount", 0);
		isStopChase = intent.getIntExtra("isStopChase", 0);
		max_jiangjin = intent.getStringExtra("max_jiangjin");
		stoptime = intent.getStringExtra("stoptime");
		type=intent.getStringExtra("type");
		rg_secrecy = (RadioGroup) findViewById(R.id.rg_secrecy);
		tab_open1 = (RadioButton) findViewById(R.id.tab_open1);
		tab_end2 = (RadioButton) findViewById(R.id.tab_end2);
		// tab_secrecy3 = (RadioButton) findViewById(R.id.tab_secrecy3);
		cb_yongyin = (CheckBox) findViewById(R.id.cb_yongyin);
		tv_money = (TextView) findViewById(R.id.tv_money);
		tv_needtopay = (TextView) findViewById(R.id.tv_needtopay);
		tv_Confirm_payment = (TextView) findViewById(R.id.tv_Confirm_payment);
		et_context = (EditText) findViewById(R.id.et_context);
		btn_back = (ImageButton) findViewById(R.id.btn_back_con);
	}

	private void enable() {
		rg_secrecy.check(R.id.tab_end2);

	}

	private void initText() {
		tv_money.setText(
				Html.fromHtml("方案金额:" + "<font color=\"#BE0205\">" + totalMoney * App.bei * 2 + "</font>" + "元"));
		tv_needtopay.setText(
				Html.fromHtml("需支付" + "<font color=\"#BE0205\">" + totalMoney * App.bei * 2 + "</font>" + "元"));
      if (type.equals("1")) {
    	  tvType.setText("投注彩种:竞彩足球");
	}else {
		tvType.setText("投注彩种:竞彩篮球");	
	}
		
	}

	private void initList() {
		tv_Confirm_payment.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		rg_secrecy.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.tab_open1:
					secrecyLevel = 0;
					break;
				case R.id.tab_end2:
					secrecyLevel = 2;
					break;
				/*
				 * case R.id.tab_secrecy3: secrecyLevel = 2; break;
				 */

				default:
					break;
				}

			}
		});

		cb_yongyin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					cancopy = true;// 可跟单，选中
				} else {
					cancopy = false;// 不可跟单，未选中
				}

			}
		});
	}

	private  long lastClickTime;

	public  boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 5000) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_Confirm_payment:
			if (isFastDoubleClick()) {
				Toast.makeText(ConfirmselectionActivity.this, "请不要在5秒内重复点击", Toast.LENGTH_SHORT).show();
			} else {
				double money = totalMoney * App.bei * 2;
				int a = new Double(money).compareTo(new Double(App.user.getBalance())+new Double(App.user.getHandselAmount()));
				if (a > 0) {
					Intent intent_alipay = new Intent();
					Bundle bundle_alipay = new Bundle();
					intent_alipay.setClass(ConfirmselectionActivity.this, AmountOfCharge.class);
					bundle_alipay.putInt("Type", 1);
					intent_alipay.putExtras(bundle_alipay);
					startActivity(intent_alipay);
				} else {
					tv_Confirm_payment.setEnabled(false);
					commitc();
				}
			}
			break;
		case R.id.btn_back_con:
			finish();
			break;

		default:
			break;
		}
	}

	private void commitc() {
		if (App.list_numbers != null) {
			if (App.list_numbers.size() > 0) {
				if (App.user != null) {
					// setEnabled(false);
					pd = BaseHelper.showProgress(ConfirmselectionActivity.this, "", "出票  ...", true, false);
					MyAsynTask myAsynTask = new MyAsynTask();
					myAsynTask.execute();
					

				} else {
					MyToast.getToast(ConfirmselectionActivity.this, "请先登陆").show();
					intent = new Intent(ConfirmselectionActivity.this, LoginActivity.class);
					intent.putExtra("loginType", "bet");
					ConfirmselectionActivity.this.startActivity(intent);
				}
			}
		} else {
			MyToast.getToast(ConfirmselectionActivity.this, "请至少选择一注").show();
		}

	}
@Override
protected void onResume() {
	// TODO Auto-generated method stub
	tv_Confirm_payment.setEnabled(true);
	super.onResume();
}
	String resultMsg;
	
	class MyAsynTask extends AsyncTask<Integer, Integer, String> {

		String error = "-1";
		long sumCount2 = sumCount * 2 * App.bei;

		@Override
		protected String doInBackground(Integer... params) {

			opt = "11";
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(ConfirmselectionActivity.this);
			
			String lottryId = App.lottery.getLotteryID();

			info = RspBodyBaseBean.changeBet_info2(lottryId, App.lottery.getIsuseId(), App.bei, 1, 1, 0, 0,
					"", "", secrecyLevel, sumCount2, sumCount, App.qi > 1 ? App.qi : 0,
					App.qi == 1 ? 0 : totalMoney, App.list_numbers, isStopChase);
			
//			Log.i(TAG, "xiadan" +App.list_numbers.toString());
			String key = App.key;
			crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			String[] values = { opt, auth, info };
//			Log.i(TAG, "xiadan" + RequestParams.convertParams(ConfirmselectionActivity.this, opt, info));
			String result = HttpUtils.doPost(App.names, values, App.path);
			System.out.println("xiadan：" + result);
			try {
				JSONObject object = new JSONObject(result);

				error = object.optString("error");
				resultMsg = object.optString("msg");
				if ("0".equals(error)) {
					App.user.setBalance(object.optDouble("balance"));
					App.user.setFreeze(object.optDouble("freeze"));
					App.schemeId = object.optInt("schemeids");
					App.lottery.setChaseTaskID(object.optInt("chasetaskids"));
					App.list_numbers.clear();
					SucJinECost = format.format(object.optDouble("currentMoeny"));
					SucCaiJinCost = format.format(object.optDouble("currentHandsel"));
					SuccMoney = format.format(object.optDouble("handselMoney"));
					App.totalCount = 0;

					// 清空所有数据

					/*
					 * Intent intent = new Intent(getApplicationContext(),
					 * PaySuccessActivity.class); //viewPagerCurrentIndex = 0;// 过关类型 0.多串1 1.多串多
					 * 
					 * intent.putExtra("paymoney", totalMoney); intent.putExtra("currentMoeny",
					 * SucJinECost); intent.putExtra("currentHandsel", SucCaiJinCost);
					 * intent.putExtra("handselMoney", SuccMoney); //intent.putExtra("max_jiangjin",
					 * Utils.decimalFormat((max_jiangjin * App.bei)));
					 * ConfirmselectionActivity.this.startActivity(intent);
					 */

				} else if (error.equals(App.ERROR_MONEY + "")) {
					LotteryUtils.showMoneyLess(ConfirmselectionActivity.this, totalMoney);
				} else if (error.equals("-500")) {
					error="-500";
				} else if (error.equals("-111")) {
					error="-111";
				} else if (error.equals("-110")) {
					error="-110";
				}  else if (error.equals("-109")) {
					error="-109";
				}
			} catch (JSONException e) {
				
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			mHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (pd != null) {
				pd.dismiss();
			}
			tv_Confirm_payment.setEnabled(true);
			switch (msg.what) {
			case 0:
				
				PayAsynTask payAsynTask = new PayAsynTask();
				payAsynTask.execute();
//				if (cancopy == true) {
//					if ((totalMoney * App.bei * 2) < 50) {
//						Intent intent = new Intent(getApplicationContext(), PaySuccessActivity.class);
//
//						intent.putExtra("paymoney", totalMoney);
//						intent.putExtra("currentMoeny", SucJinECost);
//						intent.putExtra("currentHandsel", SucCaiJinCost);
//						intent.putExtra("handselMoney", SuccMoney);
//
//						ConfirmselectionActivity.this.startActivity(intent);
//					} else {
//						PayAsynTask payAsynTask = new PayAsynTask();
//						payAsynTask.execute();
//					}
//				} else {
//					Intent intent = new Intent(getApplicationContext(), PaySuccessActivity.class);
//
//					intent.putExtra("paymoney", totalMoney);
//					intent.putExtra("currentMoeny", SucJinECost);
//					intent.putExtra("currentHandsel", SucCaiJinCost);
//					intent.putExtra("handselMoney", SuccMoney);
//
//					ConfirmselectionActivity.this.startActivity(intent);
//				}

				break;
			case 1:
				Intent intent = new Intent(getApplicationContext(), PaySuccessActivity.class);
              
				intent.putExtra("paymoney", totalMoney);
				intent.putExtra("currentMoeny", SucJinECost);
				intent.putExtra("currentHandsel", SucCaiJinCost);
				intent.putExtra("handselMoney", SuccMoney);

				ConfirmselectionActivity.this.startActivity(intent);

				break;
			case -2:
				tv_Confirm_payment.setEnabled(true);
				break;
			case -500:
				tv_Confirm_payment.setEnabled(true);
				MyToast.getToast(ConfirmselectionActivity.this, "连接超时").show();
				break;
			case -111:
				tv_Confirm_payment.setEnabled(true);
				MyToast.getToast(ConfirmselectionActivity.this, resultMsg).show();
				break;
			case -110:
				tv_Confirm_payment.setEnabled(true);
				MyToast.getToast(ConfirmselectionActivity.this, resultMsg).show();
				break;
				case -109:
					tv_Confirm_payment.setEnabled(true);
					MyToast.getToast(ConfirmselectionActivity.this, "当前非可售时间").show();
					break;
			default:
				tv_Confirm_payment.setEnabled(true);
				Toast.makeText(ConfirmselectionActivity.this, "网络异常，购买失败。请重新点击付款购买。", Toast.LENGTH_SHORT).show();
				break;
			}
			super.handleMessage(msg);
		}
	}

	class PayAsynTask extends AsyncTask<Integer, Integer, String> {

		String error = "-1";
		String conString = et_context.getText().toString();

		@Override
		protected String doInBackground(Integer... params) {

			opt = "85";
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(ConfirmselectionActivity.this);
			if (cancopy == true) {
				
				info = RspBodyBaseBean.change_TheSun2(App.schemeId + "", conString, max_jiangjin, stoptime, "1");
			}else {
				info = RspBodyBaseBean.change_TheSun2(App.schemeId + "", "", max_jiangjin, stoptime, "0");
			}
		

			String key = App.key;
			crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			String[] values = { opt, auth, info };
//			Log.i(TAG, "晒单" + RequestParams.convertParams(context, opt, info));
			String result = HttpUtils.doPost(App.names, values, App.path);
			System.out.println("晒单：" + result);
			if (result.equals("success")) {
				error = "1";
			} else {
				error = "-1";
			}

			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			mHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			backToPre();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void backToPre() {
		ExpandAdapterJCZQPassMore.clearAllDate();
		ExpandAdapterJCZQPassSingle.clearAllDate();
		App.totalCount = 0;
		for (int i = 0; i < App.activityS1.size(); i++) {
			App.activityS1.get(i).finish();
		}

	}

}
